﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace SuperMicroWave.Common
{
    public class ConnectHelper
    {
        /// <summary>
        /// 通信数据转换
        /// </summary>
        public static void Conversion(byte[] src)
        {
            byte[] tempData = new byte[2];
            int nNum = src.Length / 2;

            for (int i = 0; i < nNum; i++)
            {
                tempData[0] = src[1 + i * 2];
                tempData[1] = src[0 + i * 2];
                Array.Copy(tempData, 0, src, i * 2, 2);
            }
        }

        /// <summary>
        ///  byte[]转换为struct
        /// </summary>     
        public static object BytesToStruct(byte[] bytes, Type strcutType)
        {
            int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType)!;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

        public static ushort[] BytesToUShort(byte[] src)
        {
            int num = src.Length / 2;
            ushort[] des = new ushort[num];

            int j = 0;
            for (int i = 0; i < src.Length; i += 2)
            {
                des[j++] = BitConverter.ToUInt16(src, i);
            }
            return des;
        }
    }
}
